<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{Order, User, UserBalanceFlow, MerchantFundFlow};
use app\service\{WechatService, AlipayService, Kuaidi100Service};
use think\facade\{Db, Log};
use think\Request;

class OrderController extends BaseController
{
    /**
     * 获取订单列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 时间筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            // 订单状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 搜索条件
            if (!empty($params['keyword'])) {
                $keyword = $params['keyword'];
                $where[] = ['id|sender_name|sender_phone|receiver_name|receiver_phone', 'like', "%{$keyword}%"];
            }
            
            $list = Order::where($where)
                ->with(['user', 'coupon'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取订单列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取订单详情
     */
    public function detail(Request $request, $id)
    {
        try {
            $merchant_id = $request->merchant_id;
            
            $order = Order::where([
                'id' => $id,
                'merchant_id' => $merchant_id
            ])->with(['user', 'coupon'])->find();
            
            if (!$order) {
                return json(['code' => 1, 'msg' => '订单不存在']);
            }
            
            // 获取关联的领券订单
            if ($order->coupon_id) {
                $couponOrder = CouponOrder::where([
                    'merchant_id' => $merchant_id,
                    'user_id' => $order->user_id,
                    'business_type' => 1 // 快递业务
                ])->find();
                
                $order->coupon_order = $couponOrder;
            }
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $order]);
        } catch (\Exception $e) {
            Log::error('获取订单详情失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 退款处理
     */
    public function refund(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $order = Order::where([
                'id' => $params['order_id'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$order) {
                return json(['code' => 1, 'msg' => '订单不存在']);
            }
            
            if (!in_array($order->status, [1, 2])) { // 只有已支付和待揽收状态可退款
                return json(['code' => 1, 'msg' => '当前订单状态不可退款']);
            }
            
            // 创建退款记录
            $refund = UserRefundRecord::create([
                'merchant_id' => $merchant_id,
                'user_id' => $order->user_id,
                'order_no' => $order->id,
                'business_type' => 1, // 快递费
                'refund_amount' => $order->fee_actual,
                'refund_status' => 0 // 待退款
            ]);
            
            // 更新订单状态
            $order->save([
                'status' => 99, // 已取消
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            // 退还商家余额
            Merchant::where('id', $merchant_id)->update([
                'balance' => Db::raw('balance+' . $order->merchant_profit)
            ]);
            
            // 记录商家资金流水
            MerchantFundFlow::create([
                'merchant_id' => $merchant_id,
                'fund_flow_type' => 4, // 订单退款
                'fund_flow_amount' => -$order->merchant_profit,
                'order_no' => $order->id,
                'fund_flow_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '退款申请成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('订单退款失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 取消订单
     */
    public function cancel(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            if (empty($params['order_no'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            // 获取订单信息
            $order = Order::where([
                'order_no' => $params['order_no'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$order) {
                return json(['code' => 1, 'msg' => '订单不存在']);
            }
            
            // 检查订单状态是否可取消
            if (!in_array($order->order_status, [0, 1])) { // 0:待支付 1:待揽收
                return json(['code' => 1, 'msg' => '当前订单状态不可取消']);
            }
            
            // 调用快递100取消订单
            $kuaidi100Service = new Kuaidi100Service($merchant_id);
            $result = $kuaidi100Service->cancelOrder([
                'task_id' => $order->task_id,
                'order_id' => $order->order_no
            ]);
            
            if (!$result) {
                throw new \Exception('快递订单取消失败');
            }
            
            // 更新订单状态
            $order->save([
                'order_status' => 99, // 已取消
                'cancel_time' => date('Y-m-d H:i:s'),
                'cancel_reason' => $params['reason'] ?? '商家取消'
            ]);
            
            // 如果订单已支付，自动退款
            if ($order->pay_status == 1) {
                // 原路退款
                if ($order->payment_method == 1) { // 微信支付
                    $wechatService = new WechatService($merchant_id);
                    $result = $wechatService->refund([
                        'out_trade_no' => $order->order_no,
                        'total_fee' => $order->fee_actual * 100,
                        'refund_fee' => $order->fee_actual * 100,
                        'refund_desc' => '订单取消自动退款'
                    ]);
                    if (!$result) {
                        throw new \Exception('微信退款失败');
                    }
                } else if ($order->payment_method == 2) { // 支付宝
                    $alipayService = new AlipayService($merchant_id);
                    $result = $alipayService->refund([
                        'out_trade_no' => $order->order_no,
                        'refund_amount' => $order->fee_actual,
                        'refund_reason' => '订单取消自动退款'
                    ]);
                    if (!$result) {
                        throw new \Exception('支付宝退款失败');
                    }
                } else if ($order->payment_method == 3) { // 余额支付
                    // 退回用户余额
                    User::where('id', $order->user_id)->update([
                        'balance' => Db::raw('balance+' . $order->fee_actual)
                    ]);
                    
                    // 记录用户余额流水
                    UserBalanceFlow::create([
                        'user_id' => $order->user_id,
                        'merchant_id' => $merchant_id,
                        'type' => 4, // 退款
                        'amount' => $order->fee_actual,
                        'order_no' => $order->order_no,
                        'status' => 1,
                        'create_time' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // 更新订单退款状态
                $order->save([
                    'refund_status' => 2, // 已退款
                    'refund_time' => date('Y-m-d H:i:s'),
                    'refund_amount' => $order->fee_actual,
                    'refund_remark' => '订单取消自动退款'
                ]);
                
                // 记录商家资金流水
                MerchantFundFlow::create([
                    'merchant_id' => $merchant_id,
                    'fund_flow_type' => 4, // 退款
                    'fund_flow_amount' => -$order->fee_actual,
                    'order_no' => $order->order_no,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
            
            Db::commit();
            return json(['code' => 0, 'msg' => '取消成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('取消订单失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 